#import "PushManager.h"

@interface PushManager()<UNUserNotificationCenterDelegate>

@end

@implementation PushManager

+ (instancetype)shared {
    static PushManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PushManager alloc] init];
    });
    return instance;
}

- (void)registerRemoteNotification {
    
//    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//           center.delegate = self;
//    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert |
//    UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge |
    UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError *_Nullable error) {
        if (granted) {
            // 授权成功
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *_Nonnull settings) {
                if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSLog(@"grant authorized");
                        [[UIApplication sharedApplication] registerForRemoteNotifications];
                    });
                }
            }];
        }
    }];
}

- (void)handleDeviceToken:(NSData *)deviceToken {
    NSString *token = [self getDeviceTokenString:deviceToken];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:token forKey:@"deviceToken"];
    NSLog(@"Device Token: %@", token);
    // TODO: 将token发送给服务器
    

}

- (void)handleRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Failed to register for remote notifications: %@", error);
}
- (NSString *)getDeviceTokenString:(NSData *)deviceToken {
    const unsigned char *dataBuffer = (const unsigned char *)[deviceToken bytes];
    NSMutableString *hexString = [NSMutableString stringWithCapacity:(deviceToken.length * 2)];
    for (NSInteger i = 0; i < deviceToken.length; i++) {
        [hexString appendFormat:@"%02x", dataBuffer[i]];
    }
    
    NSLog(@"czsdvczd   %@",hexString);
//    NSLog(@"success get toke    %@", deviceToken);
//
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 13) {
            if (![deviceToken isKindOfClass:[NSData class]]) {
                return @"";
            }
            const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
            NSString *strToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                                  ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                                  ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                                  ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
//            PushDemoLog(@">=ios13 Get FINAL TOKEN");
//            APN_TOKEN = strToken;
        return  strToken;;
//            return;
        } else {
            NSString *token = [NSString stringWithFormat:@"%@", deviceToken];
            token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
            token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
            token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//            PushDemoLog(@"Get FINAL TOKEN");
//            APN_TOKEN = token;
            return  token;
        }
    
//    return [hexString copy];
}

// 发送本地推送
- (void)sendLocalNotificationWithTitle:(NSString *)title message:(NSString *)message {
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = title;
    content.body = message;
    content.sound = [UNNotificationSound defaultSound];
    
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    
    NSString *identifier = @"LocalNotification";
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
    
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error) {
            NSLog(@"本地推送添加失败：%@", error);
        }
    }];
   
}

#pragma mark - UNUserNotificationCenterDelegate
// 应用在前台收到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    if (@available(iOS 14.0, *)) {
          completionHandler(UNNotificationPresentationOptionBanner |
                          UNNotificationPresentationOptionSound |
                          UNNotificationPresentationOptionBadge |
                          UNNotificationPresentationOptionList);
      } else {
          completionHandler(UNNotificationPresentationOptionAlert |
                          UNNotificationPresentationOptionSound |
                          UNNotificationPresentationOptionBadge);
      }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

//    [self processRecvMsg:userInfo];
}


// 点击通知进入应用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    // TODO: 处理推送点击事件
    NSLog(@"点击了推送消息: %@", userInfo);
    completionHandler();
}

@end 
